package nethelp

import (
	"bytes"
	"errors"
	"fmt"
	"github.com/go-resty/resty/v2"
	"io"
	"net/http"
	"os"
	"path"
	"path/filepath"
	"time"
)

type RClient struct {
	client  *resty.Client
	timeout time.Duration
}

// init 初始化客户端
func (c *RClient) init() *RClient {
	c.client = resty.New()
	c.client = c.client.
		SetHeader("Content-Type", "application/json").
		SetHeader("Accept", "application/json")
	/*
		配置Transport以启用Keep-Alive
	*/
	c.client = c.client.SetTransport(&http.Transport{
		MaxIdleConns:        100,
		MaxIdleConnsPerHost: 100,
		IdleConnTimeout:     90 * time.Second,
	})
	if c.timeout.Seconds() == 0 {
		c.client.SetTimeout(10 * time.Second)
	} else {
		c.client.SetTimeout(c.timeout)
	}
	return c
}

// SetTimeOut 设置请求超时时长
func (c *RClient) SetTimeOut(timeOut time.Duration) *RClient {
	c.timeout = timeOut
	c.init()
	return c
}

func (c *RClient) Get(url string, headers, params map[string]string) (resp *resty.Response, err error) {
	req := c.client.R()
	if params != nil && len(params) != 0 {
		req = req.SetQueryParams(params)
	}
	if headers != nil && len(headers) != 0 {
		for k, v := range headers {
			req.SetHeader(k, v)
		}
	}
	resp, err = req.Get(url)
	if err != nil {
		return
	}
	return
}

func (c *RClient) Post(url string, headers map[string]string, body any) (resp *resty.Response, err error) {
	req := c.client.R()
	if headers != nil && len(headers) != 0 {
		for k, v := range headers {
			req.SetHeader(k, v)
		}
	}
	resp, err = req.
		SetBody(body).
		Post(url)
	if err != nil {
		return
	}
	return
}

// Download 下载文件
func (c *RClient) Download(url, saveDir, fileName string) (err error) {
	resp, err := c.client.R().Get(url)
	if err != nil {
		return
	}
	if resp.StatusCode() != 200 {
		return errors.New(fmt.Sprintf("%v\n网络请求错误code：%v", url, resp.StatusCode()))
	}
	if fileName == "" {
		_, fileName = path.Split(url)
	}
	savePath := filepath.Join(saveDir, fileName)
	out, err := os.Create(savePath)
	if err != nil {
		return
	}
	defer out.Close()
	_, err = io.Copy(out, bytes.NewReader(resp.Body()))
	return
}
